//
//  FirstViewController.swift
//  miaoyin
//
//  Created by David on 2017/2/14.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

//    var scrollView: UIScrollView!
    var tableView: UITableView!
    
    var slider: LLSlider!
    var sliderData: NSArray?
//    var sliderImg: [UIImageView] = []
    
    var contributeBtn: UIButton!
    var feedBackBtn: UIButton!
    
//    var categoryList: UITableView!
    var categoryList: UIStackView!
    var categorys:NSArray?
    
    var categoryItemHeight: CGFloat!
    
    var spotList: UITableView!
    var articleList: NSArray?
    
    var refreshControl: UDRefreshControl!
    var pageControl: UDRefreshControl!
    var currentPage = 1
    
    
    var cardView: CardBlurView!
    var cardViewLabel: UILabel!
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "发现"
//        print(view.frame.width-32)
//        scrollView = UIScrollView(frame: view.frame)
//        scrollView.alwaysBounceVertical = true
//        view.addSubview(scrollView)
        
        tableView = UITableView(frame: view.frame, style: .grouped)
        tableView.tag = 3489
        tableView.backgroundColor = UIColor.extraLightGray
        tableView.separatorStyle = .none
        
        view.addSubview(tableView)
        
        slider = LLSlider(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.width*0.5))
        slider.backgroundColor = UIColor.lightGray
//        scrollView.addSubview(slider)
        
//        let iv1 = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
//        iv1.backgroundColor = UIColor.orange
//        let l1 = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
//        l1.text = "adsf"
//        iv1.addSubview(l1)
//        let iv2 = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
//        iv2.backgroundColor = UIColor.purple
//        slider.imageViews = [iv1, iv2]
        
        contributeBtn = UIButton(frame: CGRect(x: 16, y: slider.frame.height + 8, width: (view.bounds.width - 40)/2, height: 36))
        contributeBtn.setTitle("投 稿", for: .normal)
        contributeBtn.setTitleColor(UIColor.gray, for: .normal)
        contributeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//        contributeBtn.layer.borderColor = themeColor1.cgColor
//        contributeBtn.layer.borderWidth = 1
        contributeBtn.layer.cornerRadius = 8
        contributeBtn.backgroundColor = UIColor.extraLightGray
        contributeBtn.addTarget(self, action: #selector(FirstViewController.openContribute), for: .touchUpInside)
        
        feedBackBtn = UIButton(frame: CGRect(x: view.bounds.width/2 + 8, y: slider.frame.height + 8, width: (view.bounds.width - 40)/2, height: 36))
        feedBackBtn.setTitle("反 馈", for: .normal)
        feedBackBtn.setTitleColor(UIColor.gray, for: .normal)
        feedBackBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//        feedBackBtn.layer.borderColor = themeColor1.cgColor
//        feedBackBtn.layer.borderWidth = 1
        feedBackBtn.layer.cornerRadius = 8
        feedBackBtn.backgroundColor = UIColor.extraLightGray
        feedBackBtn.addTarget(self, action: #selector(FirstViewController.openFeedback), for: .touchUpInside)
//        categorys = ["社会\nSociety", "ACG", "音乐\nMusic", "运动\nSports", "趣味\nFun", "艺术\nArt", "生活\nLifestyle", "影视\nFlim&TV", "时尚\nFashion", "设计\nDesign", "科技\nTech", "阅读\nBooks", "科普\nScience", "造物主\nCreator"]
        
        categoryItemHeight = (view.frame.width - 32)/4
        self.categorys = [["id":"3", "name":"设计\nDesign"],["id":"15", "name":"好奇\nCurious"],["id":"14", "name":"阅读\nRead"],["id":"12", "name":"搜罗\nCollecting"]]
//        categoryList = UITableView(frame: CGRect(x: 0, y: 0, width: categoryItemHeight + 32, height: view.bounds.width))
//        categoryList.separatorStyle = .none
//        categoryList.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI/2))
//        categoryList.center = CGPoint(x: view.center.x, y: slider.frame.height + 48 + (categoryItemHeight + 32)/2)
//        categoryList.tag = 348
//        categoryList.delegate = self
//        categoryList.dataSource = self
//        categoryList.showsVerticalScrollIndicator = false
//        scrollView.addSubview(categoryList)

        categoryList = UIStackView(frame: CGRect(x: 0, y: 0, width: view.frame.width - 32, height: categoryItemHeight*0.75))
        categoryList.center = CGPoint(x: view.center.x, y: slider.frame.height + 52 + (categoryItemHeight*0.75)/2)
        categoryList.distribution = .fillEqually
        categoryList.axis = .horizontal
        categoryList.spacing = 4
//        categoryList.alignment = .center
        for cat in 0..<categorys!.count{
            let catView = UIView(frame: CGRect(x: 0, y: 0, width: categoryItemHeight, height: categoryItemHeight*0.75))
            catView.layer.cornerRadius = 4
            catView.layer.masksToBounds = true
            
            let catImg = UIImageView(frame: CGRect(x: 0, y: 0, width: categoryItemHeight, height: catView.frame.height))
            catImg.backgroundColor = themeColor2
            catImg.image = UIImage(named: "cat\(cat+1)")
            catImg.layer.cornerRadius = 4
            catView.addSubview(catImg)
            
            let catBtn = UIButton(frame: CGRect(x: 0, y: 0, width: categoryItemHeight, height: catView.frame.height))
            catBtn.tag = cat
            catBtn.backgroundColor = UIColor(white: 0, alpha: 0.5)
            catBtn.setTitleColor(UIColor.white, for: .normal)
            catBtn.layer.cornerRadius = 4
//            catBtn.contentHorizontalAlignment = .center
//            catBtn.contentMode = .center
            catBtn.addTarget(self, action: #selector(FirstViewController.gotoCategory(btn:)), for: .touchUpInside)
            
            let showStr = (categorys?.object(at: cat) as! NSDictionary).object(forKey: "name") as! String
            let sep = showStr.components(separatedBy: "\n")
            let attrStr = NSMutableAttributedString(string: showStr)
            attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSMakeRange(0, showStr.characters.count))
            attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(0, sep[0].characters.count))
            if sep.count > 1{
                attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 12), range: NSMakeRange(sep[0].characters.count+1, sep[1].characters.count))
            }
            catBtn.setAttributedTitle(attrStr, for: .normal)
            catBtn.titleLabel?.numberOfLines = 0
            catBtn.titleLabel?.textAlignment = .center
            catView.addSubview(catBtn)
            
            categoryList.addArrangedSubview(catView)
        }
        
        
        tableView.delegate = self
        tableView.dataSource = self
        
        refreshControl = UDRefreshControl(frame: CGRect(x: 0, y: -96, width: view.bounds.width, height: 64))
        tableView.addSubview(refreshControl)
        
        pageControl = UDRefreshControl(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 64))
        pageControl.normalTitle = "加载更多"
        tableView.tableFooterView = pageControl
        
        loadLocalData()
        
        cardView = CardBlurView(frame: view.frame)
        view.addSubview(cardView)
        cardView.alpha = 0
        
        cardViewLabel = UILabel(frame: CGRect(x: 0, y: 0, width: cardView.cardView.frame.width - 32, height: cardView.cardView.frame.height-32))
        cardViewLabel.center = CGPoint(x: cardView.cardView.frame.width / 2, y: cardView.cardView.frame.height / 2)
        cardViewLabel.textAlignment = .center
        cardViewLabel.font = UIFont.systemFont(ofSize: 14)
        cardViewLabel.textColor = themeColor2
        cardViewLabel.numberOfLines = 0
//        cardViewLabel.text = 
        cardView.cardView.addSubview(cardViewLabel)
        
        checkLogin()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//        print(scrollView.contentOffset.y)
        if scrollView.contentOffset.y < -150{
            if refreshControl.state == .normal{
                refreshControl.readyToRefresh()
            }
            
        }else{
            if refreshControl.state == .ready{
                refreshControl.endRefresh()
            }
            
        }
        
//        let totalHeight = slider.frame.height + categoryItemHeight*0.75 + 24 + 40 + 280*CGFloat(articleList?.count ?? 0) - view.frame.height + 64
        let totalHeight = tableView.contentSize.height - tableView.frame.height + 96
//        print("\(scrollView.contentOffset.y) : \(totalHeight)")
        
        if scrollView.contentOffset.y >= totalHeight {
            if pageControl.state == .normal{
                pageControl.readyToRefresh()
            }
        }else{
            if pageControl.state == .ready{
                pageControl.endRefresh()
            }
        }
        
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if refreshControl.state == .ready{
            refreshSpotPage()
        }
        if pageControl.state == .ready {
            getPage()
        }
    }
    
    func checkLogin(){
        
        let checkResq = URLRequest(url: URL(string: "\(baseDomainName)/print/?m=admin&c=login&a=userislogin")!)
        
        
//        let cookies = HTTPCookieStorage.shared.cookies!
        
        let cookieData = UserDefaults.standard.object(forKey: cookieKey) as? Data
        if cookieData != nil{
            let cookies = NSKeyedUnarchiver.unarchiveObject(with: cookieData!)  as? [HTTPCookie]
            if cookies != nil{
                
                HTTPCookieStorage.shared.setCookies(cookies!, for: URL(string: baseDomainName)!, mainDocumentURL: nil)
//                let cookiesHeader = HTTPCookie.requestHeaderFields(with: cookies!)
//                print(cookiesHeader)
//                checkResq.setValue(cookiesHeader["Cookie"], forHTTPHeaderField: "Cookie")
            }
            
        }
        
        
        
        
        URLSession.shared.dataTask(with: checkResq) { (data:Data?, resp:URLResponse?, err:Error?) in
            do{
                if err != nil{
                    throw err!
                }
                print(String(data: data!, encoding: .utf8) ?? "data nil")
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                let code = jsonObj?.object(forKey: "code") as? Int
                if code != nil{
                    if code != 200{
                        UserDefaults.standard.removeObject(forKey: loginUserDefaultKeyName)
                    }
                }
            }catch let ex{
                
                print(ex)
            }
        }.resume()
    }
    
    func loadLocalData(){
        let file = "\(CACHES_PATH)/\(spotPageDataFileName)"
        print(file)
        do{
            let data = try NSData(contentsOfFile: file) as Data
            let jsonObj = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary
            let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
            
            // 分类菜单
            self.categorys = jsonData?.object(forKey: "menu") as? NSArray
            // 轮播图
            self.sliderData = jsonData?.object(forKey: "topSmailNews") as? NSArray
            // 文章
            self.articleList = jsonData?.object(forKey: "listNews") as? NSArray
            print(articleList?.count ?? 0)
            
            // UI
//            self.categoryList.reloadData()
            self.reloadSliderImg()
            self.tableView.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .none)
            
            
            
        }catch let err{
            print(err)
//            refreshSpotPage()
        }
        
    }
    
    func refreshSpotPage(){
        refreshControl.beginRefresh()
        var insert = tableView.contentInset
        insert.top += 96
        self.tableView.contentInset = insert
        
        
        
        let resq = URLRequest(url: URL(string: "\(baseDomainName)/cms/index.php?type=m")!)
//        var resq = URLRequest(url: URL(string: "\(baseDomainName)/index.php?type=m")!)
//        let ua = UIWebView().stringByEvaluatingJavaScript(from: "navigator.userAgent")
//        
//        if ua != nil {
//            print(ua!)
//            resq.setValue(ua!, forHTTPHeaderField: "User-Agent")
//        }
        
        
        URLSession.shared.dataTask(with: resq) { (data:Data?, resp:URLResponse?, err:Error?) in
            do{
                DispatchQueue.main.async {
                    self.refreshControl.endRefresh()
                    var insert = self.tableView.contentInset
                    insert.top -= 96
//                    self.tableView.contentInset = insert
                    UIView.animate(withDuration: 0.3, animations: {
//                        self.tableView.setContentOffset(CGPoint(x: 0, y: self.tableView.contentOffset.y), animated: true)
                        self.tableView.contentInset = insert
                        
                    })
                }
                if err != nil{
                    throw err!
                }
                // MARK:写入本地缓存
                if data == nil{
                    throw NSError(domain: "dataNil", code: 9, userInfo: nil)
                }
                (data! as NSData).write(toFile: "\(CACHES_PATH)/\(spotPageDataFileName)", atomically: true)
                print(String(data: data!, encoding: .utf8) ?? "data not utf8 string")
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                
                let format = DateFormatter()
                format.dateFormat = "yyyy-MM-dd HH:mm:ss"
                UserDefaults.standard.set(format.string(from: Date()), forKey: spotRefreshedTimeKey)
                
                // 分类菜单
                self.categorys = jsonData?.object(forKey: "menu") as? NSArray
                // 轮播图
                self.sliderData = jsonData?.object(forKey: "topSmailNews") as? NSArray
                // 文章
                self.articleList = jsonData?.object(forKey: "listNews") as? NSArray
                
                
                // UI
                DispatchQueue.main.async {
//                    self.categoryList.reloadData()
                    self.reloadSliderImg()
                    
                    self.tableView.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .none)
                }
                
            }catch let ex{
                let alert = UIAlertController(title: "服务器出错", message: nil, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                DispatchQueue.main.async {
                    self.present(alert, animated: true, completion: nil)
                }
                
                print(ex)
            }
        }.resume()
        
        
    }
    
    func getPage(){
        pageControl.beginRefresh()
        
        let p = currentPage + 1
        print(p)
        let resq = URLRequest(url: URL(string: "\(baseDomainName)/cms/index.php?type=m&page=\(p)")!)
        
        URLSession.shared.dataTask(with: resq) { (data:Data?, resp:URLResponse?, err:Error?) in
            do{
                DispatchQueue.main.async {
                    self.pageControl.endRefresh()
                }
                if err != nil{
                    throw err!
                }
                if data == nil{
                    throw NSError(domain: "dataNil", code: 9, userInfo: nil)
                }
                print(String(data: data!, encoding: .utf8) ?? "data nil")
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                
                let format = DateFormatter()
                format.dateFormat = "yyyy-MM-dd HH:mm:ss"
                UserDefaults.standard.set(format.string(from: Date()), forKey: spotRefreshedTimeKey)
                
                // 文章
                let listNews = jsonData?.object(forKey: "listNews") as? NSArray
                if listNews != nil{
                    if self.articleList != nil{
                        self.articleList = self.articleList!.addingObjects(from: listNews as! [Any]) as NSArray
                        self.currentPage += 1
                    }else{
                        self.articleList = listNews
                        self.currentPage = 1
                    }
                    
                }
                
                
                // UI
                DispatchQueue.main.async {
                    
//                    self.tableView.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .none)
                    self.tableView.reloadData()
                    
                    if listNews == nil{
                        self.pageControl.normalTitle = "没有更多了"
                    }else{
                        if listNews!.count == 0{
                            self.pageControl.normalTitle = "没有更多了"
                        }else{
                            self.pageControl.normalTitle = "加载更多"
                        }
                    }
                }
                
            }catch let ex{
                let alert = UIAlertController(title: "服务器出错", message: nil, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                DispatchQueue.main.async {
                    self.present(alert, animated: true, completion: nil)
                }
                
                print(ex)
            }
            }.resume()
        
        
    }
    
    func reloadSliderImg(){
        if sliderData == nil{
            return
        }
        var iva:[UIButton] = []
        
        var firstImg: UIImage?
        var lastImg: UIImage?
        
        for s in 0..<sliderData!.count{
            let sdata = sliderData?.object(at: s) as? NSDictionary
            let retImgUrl = sdata?.object(forKey: "thumb") as? String
            if retImgUrl == nil{
                break
            }
            let iv = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
            iv.tag = s
            iv.backgroundColor = UIColor.lightGray
            iv.imageView?.contentMode = .scaleAspectFill
            iv.adjustsImageWhenHighlighted = false
//            iv.contentMode = .scaleAspectFill
            iv.addTarget(self, action: #selector(FirstViewController.sliderImgClick(img:)), for: .touchUpInside)
            iva.append(iv)
            let filename = retImgUrl?.components(separatedBy: "/").last
            
            var localImgLoaded = false
            if filename != nil{
                let img = UIImage(contentsOfFile: "\(imageCachesFloderPath)/\(filename!)")
                if img != nil{
//                    iv.image = img
                    iv.setImage(img, for: .normal)
                    localImgLoaded = true
                    if s == 0{
                        lastImg = img
                    }
                    if s == self.sliderData!.count - 1{
                        firstImg = img
                    }
                }
            }
            
            if !localImgLoaded{
                
                let imgUrl = URL(string: "\(baseDomainName)/\(retImgUrl!)")
                if imgUrl == nil{
                    break
                }
                
                URLSession.shared.dataTask(with: imgUrl!, completionHandler: { (data:Data?, resp:URLResponse?, err:Error?) in
                    if err != nil{
                        return
                    }
                    if data == nil{
                        return
                    }
                    // 本地缓存
                    (data! as NSData).write(toFile: "\(imageCachesFloderPath)/\(filename ?? "s\(s).jpg")", atomically: true)
                    
                    DispatchQueue.main.async {
//                        iv.image = UIImage(data: data!)
                        iv.setImage(UIImage(data: data!), for: .normal)
                        if s == 0{
                            lastImg = UIImage(data: data!)
                        }
                        if s == self.sliderData!.count - 1{
                            firstImg = UIImage(data: data!)
                        }
                    }
                    
                }).resume()
            }
            
        }
        if iva.count > 0{
            slider.imageViews = iva
            self.slider.endImageView?.setImage(lastImg, for: .normal)
            self.slider.endImageView?.imageView?.contentMode = .scaleAspectFill
            self.slider.startImageView?.setImage(firstImg, for: .normal)
            self.slider.startImageView?.imageView?.contentMode = .scaleAspectFill
        }
    }
    
    func sliderImgClick(img: UIButton){
        //MARK: 轮播图点击
        print("slider\(img.tag)")
        if sliderData != nil{
            let sliderItem = sliderData?.object(at: img.tag) as? NSDictionary
            let weburlstr = sliderItem?.object(forKey: "url") as? String
            let aid = sliderItem?.object(forKey: "news_id") as? String
            var fromMy = true
            if weburlstr != nil{
                let weburl = URL(string: weburlstr!)
                if weburl != nil{
                    fromMy = false
                    hidesBottomBarWhenPushed = true
                    navigationController?.pushViewController(WebArticleViewController(title: title ?? "文章", url: weburl!, id: aid), animated: true)
                }
                
            }
            
            if fromMy{
                
                if aid != nil{
                    hidesBottomBarWhenPushed = true
                    navigationController?.pushViewController(FCArticleViewController(title: title ?? "文章", id: aid!), animated: true)
                }
            }
            
            
        }
    }
    
    func gotoCategory(btn: UIButton){
        if categorys != nil {
            hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(CategoryViewController(tab: btn.tag, tabItems: categorys), animated: true)
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        var tempDataLoaded = false
        if sliderData != nil && articleList != nil {
            if sliderData!.count > 0 && articleList!.count > 0 {
                tempDataLoaded = true
            }
            
        }
        
        if tempDataLoaded{
            let refreshTime = UserDefaults.standard.object(forKey: spotRefreshedTimeKey) as? String
            if refreshTime != nil{
                let format = DateFormatter()
                format.dateFormat = "yyyy-MM-dd HH:mm:ss"
                let reDate = format.date(from: refreshTime!)
                if reDate != nil{
                    
                    if reDate!.timeIntervalSince(Date()) < -86400.0 {
                        refreshSpotPage()
                    }
                }
            }
        }else{
            if UserDefaults.standard.object(forKey: firstLaunchKey) != nil{
                refreshSpotPage()
            }
        }
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        switch tableView.tag {
        case self.tableView.tag:
            return 2
        default:
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch tableView.tag {
//        case categoryList.tag:
//            if categorys != nil{
//                return categorys!.count
//            }
//            return 0
        case self.tableView.tag:
            if section == 0{
                return 1
            }else if section == 1{
                if articleList != nil{
                    return articleList!.count
                }
                return 0
            }
            return 1
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch tableView.tag {
//        case categoryList.tag:
//            return categoryItemHeight + 8
        case self.tableView.tag:
            if indexPath.section == 0 && indexPath.row == 0{
                return slider.frame.height + categoryItemHeight*0.75 + 24 + 40
            }
            return 272
        default:
            return 44
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch tableView.tag {
        case self.tableView.tag:
            if section == 0{
                return 0.001
            }
            if section == 1{
                return 0.001
            }
            return 1
        default:
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        switch tableView.tag {
        case self.tableView.tag:
            if section == 0{
                return 8
            }
            return 0
        default:
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "item")
        switch tableView.tag {
        /*
        case categoryList.tag:
            cell.selectionStyle = .none
            let item = UIView(frame: CGRect(x: 16, y: 4, width: categoryItemHeight*0.75, height: categoryItemHeight))
            item.backgroundColor = UIColor(white: 0, alpha: 0.5)
            item.layer.cornerRadius = 4
            
            let icon = UIImageView(frame: CGRect(x: 16, y: 4, width: categoryItemHeight*0.75, height: categoryItemHeight))
            icon.image = UIImage(named: "cat\(indexPath.row+1)")
            icon.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI/2))
            icon.contentMode = .scaleAspectFill
            icon.layer.masksToBounds = true
            icon.layer.cornerRadius = 4
            cell.addSubview(icon)
            
            let textLabel = UILabel(frame: CGRect(x: 0, y: 0, width: categoryItemHeight*0.75, height: categoryItemHeight))
            textLabel.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI/2))
            textLabel.numberOfLines = 0
            textLabel.textAlignment = .center
            textLabel.textColor = UIColor.white
            textLabel.font = UIFont.systemFont(ofSize: 14)
            
            item.addSubview(textLabel)
            
            cell.addSubview(item)
            
            if categorys != nil {
                let catInfo = categorys?.object(at: indexPath.row) as? NSDictionary
                textLabel.text = catInfo?.object(forKey: "name") as? String
            }
            
            break
        */
        case self.tableView.tag:
            if indexPath.section == 0 && indexPath.row == 0{
                
                cell.selectionStyle = .none
                cell.addSubview(slider)
                cell.addSubview(contributeBtn)
                cell.addSubview(feedBackBtn)
                
//                let line = UIView(frame: CGRect(x: 0, y: categoryList.center.y - categoryList.frame.height/2 - 16, width: view.frame.width, height: 8))
//                line.backgroundColor = UIColor.extraLightGray
//                cell.addSubview(line)
                
                cell.addSubview(categoryList)
            }
            if indexPath.section == 1{
//                let bgview = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 256))
//                bgview.backgroundColor = themeColor1
//                cell.selectedBackgroundView = bgview
                cell.selectionStyle = .none
                let dateLabel = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width - 32 - 64, height: 20))
                dateLabel.font = UIFont.systemFont(ofSize: 14)
                dateLabel.textColor = UIColor.lightGray
                cell.addSubview(dateLabel)
                
                let sepBorder = UIView(frame: CGRect(x: view.bounds.width - 24 - 48, y: 8, width: 4, height: 20))
                sepBorder.backgroundColor = themeColor1
                cell.addSubview(sepBorder)
                
                let categoryLabel = UILabel(frame: CGRect(x: view.bounds.width - 24 - 44, y: 8, width: 44, height: 20))
                categoryLabel.font = UIFont.systemFont(ofSize: 14)
                categoryLabel.textAlignment = .right
                cell.addSubview(categoryLabel)
                
                let imageView = UIImageView(frame: CGRect(x: 16, y: 36, width: view.bounds.width - 32, height: 144))
                imageView.backgroundColor = UIColor.lightGray
                imageView.contentMode = .scaleAspectFill
                imageView.layer.masksToBounds = true
                cell.addSubview(imageView)
                
                let titleLabel = UILabel(frame: CGRect(x: 16, y: 188, width: view.bounds.width - 32, height: 24))
                titleLabel.font = UIFont.systemFont(ofSize: 20)
                cell.addSubview(titleLabel)
                
                let contentLabel = UILabel(frame: CGRect(x: 16, y: 220, width: view.bounds.width - 32, height: 20))
                contentLabel.font = UIFont.systemFont(ofSize: 14)
                contentLabel.textColor = UIColor.lightGray
//                contentLabel.isEditable = false
//                contentLabel.isSelectable = false
//                contentLabel.isScrollEnabled = false
//                contentLabel.numberOfLines = 0
//                contentLabel.layer.masksToBounds = true
                cell.addSubview(contentLabel)
                
//                let articleLabel = UILabel(frame: CGRect(x: 16, y: 184, width: view.bounds.width - 32, height: 64))
//                articleLabel.numberOfLines = 3
//                cell.addSubview(articleLabel)
                
//                let likeBtn = UIButton(frame: CGRect(x: view.frame.width - 44 - 88, y: 264, width: 80, height: 20))
//                likeBtn.setImage(#imageLiteral(resourceName: "like"), for: .normal)
//                likeBtn.imageView?.contentMode = .scaleAspectFit
//                likeBtn.setTitle("999+", for: .normal)
//                likeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//                likeBtn.setTitleColor(UIColor.gray, for: .normal)
//                cell.addSubview(likeBtn)
//                
//                let shareBtn = UIButton(frame: CGRect(x: view.frame.width - 44, y: 264, width: 24, height: 20))
//                shareBtn.setImage(#imageLiteral(resourceName: "share"), for: .normal)
//                shareBtn.imageView?.contentMode = .scaleAspectFit
//                cell.addSubview(shareBtn)
                
                let line = UIView(frame: CGRect(x: 0, y: 264, width: view.frame.width, height: 8))
                line.backgroundColor = UIColor.extraLightGray
                cell.addSubview(line)
                
                
                if articleList != nil{
                    
                    let articleInfo = articleList?.object(at: indexPath.row) as? NSDictionary
                    let createTime = articleInfo?.object(forKey: "create_time") as? String
                    dateLabel.text = softDate(createTime ?? "")//"2017-02-17"
                    categoryLabel.text = articleInfo?.object(forKey: "cat_name") as? String ?? "分类"//"设计"
                    
                    
                    
                    titleLabel.text = articleInfo?.object(forKey: "title") as? String//"标题"
//                    let title = articleInfo?.object(forKey: "title") as? String
//                    if title != nil{
//                        var articleStr = ""
//                        let maxCount = Int(view.frame.width/21)
//                        var titleTrim = title!
//                        if title!.characters.count > maxCount {
//                            titleTrim = title!.substring(to: title!.index(title!.startIndex, offsetBy: maxCount-2))
//                            titleTrim += "..."
//                        }
//                        
//                        articleStr += titleTrim
//                        let content = articleInfo?.object(forKey: "description") as? String
//                        if content != ""{
//                            articleStr += "\n\n"
//                            articleStr += content ?? ""
//                        }
//                        
//                        
//                        let attrStr = NSMutableAttributedString(string: articleStr)
//                        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.black, range: NSMakeRange(0, titleTrim.characters.count))
//                        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGray, range: NSMakeRange(titleTrim.characters.count, (content != "" ? content!.characters.count + 2 : 0)))
//                        attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 20), range: NSMakeRange(0, titleTrim.characters.count))
//                        attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(titleTrim.characters.count, (content != "" ? content!.characters.count + 2 : 0)))
//                        
//                        articleLabel.attributedText = attrStr
//                    }
                    
                    contentLabel.text = articleInfo?.object(forKey: "description") as? String//"内容"
//                    contentLabel.sizeToFit()
                    
                    let retImgUrl = articleInfo?.object(forKey: "thumb") as? String
                    
                    
                    if retImgUrl != nil{
                        let filename = retImgUrl?.components(separatedBy: "/").last
                        
                        var localImgLoaded = false
                        if filename != nil{
                            let img = UIImage(contentsOfFile: "\(imageCachesFloderPath)/\(filename!)")
                            if img != nil{
                                imageView.image = img
                                localImgLoaded = true
                            }
                        }
                        
                        if !localImgLoaded{
                            let imgUrl = URL(string: "\(baseDomainName)/\(retImgUrl!)")
                            if imgUrl != nil{
                                URLSession.shared.dataTask(with: imgUrl!, completionHandler: { (data:Data?, resp:URLResponse?, err:Error?) in
                                    if err != nil{
                                        return
                                    }
                                    if data == nil{
                                        return
                                    }
                                    (data! as NSData).write(toFile: "\(imageCachesFloderPath)/\(filename ?? "a\(indexPath.row).jpg")", atomically: true)
                                    DispatchQueue.main.async {
                                        imageView.image = UIImage(data: data!)
                                    }
                                    
                                }).resume()
                                
                            }
                        }
                        
                    }
                    
                    
                }
                
                
            }
            break
        default:
            break
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch tableView.tag {
        case categoryList.tag:
            if categorys != nil {
//                var tabTitles = NSMutableArray()
//                for i in categorys!{
//                    
//                    tabTitles.append(categorys?.object(at: i))
//                }
                hidesBottomBarWhenPushed = true
                navigationController?.pushViewController(CategoryViewController(tab: indexPath.row, tabItems: categorys), animated: true)
            }
            
            break
        case self.tableView.tag:
            if indexPath.section == 1{
                tableView.deselectRow(at: indexPath, animated: true)
                if articleList != nil{
                    
                    let articleInfo = articleList?.object(at: indexPath.row) as? NSDictionary
                    let weburlstr = articleInfo?.object(forKey: "url") as? String
                    let title = articleInfo?.object(forKey: "title") as? String
                    let aid = articleInfo?.object(forKey: "news_id") as? String
                    var fromMy = true
                    if weburlstr != nil{
                        let weburl = URL(string: weburlstr!)
                        if weburl != nil{
                            fromMy = false
                            hidesBottomBarWhenPushed = true
                            let articleVC = WebArticleViewController(title: title ?? "文章", url: weburl!, id: aid)
                            navigationController?.pushViewController(articleVC, animated: true)
                            
                            let retImgUrl = articleInfo?.object(forKey: "thumb") as? String
                            
                            var imgToShare: UIImage?
                            
                            if retImgUrl != nil{
                                let filename = retImgUrl?.components(separatedBy: "/").last
                                
                                if filename != nil{
                                    let img = UIImage(contentsOfFile: "\(imageCachesFloderPath)/\(filename!)")
                                    if img != nil{
                                        imgToShare = img
                                    }
                                }
                                
                                
                            }
                            
                            articleVC.shareObj = FCSharingObj(title: title, description: articleInfo?.object(forKey: "description") as? String, thumb: imgToShare, url: weburlstr)
                        }
                        
                    }
                    
                    if fromMy{
                        
                        if aid != nil{
                            hidesBottomBarWhenPushed = true
                            navigationController?.pushViewController(FCArticleViewController(title: title ?? "文章", id: aid!), animated: true)
                        }
                    }
                    
                    
                }
            }
            break
        default:
            break
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        hidesBottomBarWhenPushed = false
    }

    func openContribute(){
        cardViewLabel.text = contributeText
        UIView.animate(withDuration: 0.3) {
            self.cardView.alpha = 1
        }
    }
    
    func openFeedback(){
        cardViewLabel.text = feedbackText
        UIView.animate(withDuration: 0.3) {
            self.cardView.alpha = 1
        }
    }

    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

